﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CDSBDemandControl.Presenter;
using System.Web.UI.HtmlControls;
using CDSBDemandControl.Model;
using System.Drawing;

namespace CDSBDemandControl.View.Web.PaginasInternas
{
    public partial class AlocacaoAnual : System.Web.UI.Page, IDiscriminatorDemand
    {
        private Presenter.DiscriminatorDemand Presenter;
        public string caption = "Previsão de Alocação referente ao ano {0}.";
        public int[] sumarizador;
        public int[] sumarizadorModulo;
        public int[] sumarizadorTotal;
        public int[] sumarizadorDisponibilidade;

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetExpires(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (!this.IsPostBack || this.Session["Presenter"] == null)
            {
                this.Presenter = new DiscriminatorDemand(this);

                this.Session["Presenter"] = this.Presenter;

                if (!this.IsPostBack)
                    this.ListarAlocacao();
            }
            else
            {
                this.Presenter = (Presenter.DiscriminatorDemand)this.Session["Presenter"];
                this.Presenter.ResetView(this);
            }

            this.GeneratePaginator(Int32.Parse(Session["numberOfFrames"].ToString()));            
        }

        private Panel RetornaPainelLink()
        {
            Panel pnl = new Panel();
            LinkButton lnkMensal = new LinkButton();
            lnkMensal.Click += new EventHandler(lnkMensal_Click);
            lnkMensal.ID = "lnkAnual";
            lnkMensal.Text = "Relatório Mensal";
            lnkMensal.BackColor = Color.White;
            lnkMensal.ForeColor = Color.FromArgb(88, 00, 00);
            pnl.Controls.Add(lnkMensal);

            return pnl;
        }

        void lnkMensal_Click(object sender, EventArgs e)
        {
            Response.Redirect("Alocacao.aspx");
        }

        private void ListarAlocacao()
        {
            this.Presenter.ListarPrevisaoAlocacao();
        }

        void IDiscriminatorDemand.ExibirAlocacao(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            Session["demandModels"] = demandModels;
            
            List<DateTime> feriados = this.Presenter.getFeriados();
            Session["feriados"] = feriados;

            DateTime? dtInicioPeriodo = demandModels.Min(x => x.EstimatedStart);
            DateTime? dtFinalPeriodo = demandModels.Max(x => x.EstimatedConclude);

            DateTime tmStart = new DateTime(dtInicioPeriodo.Value.Year, dtInicioPeriodo.Value.Month, 1);
            DateTime tmEnd = new DateTime(dtFinalPeriodo.Value.Year, dtFinalPeriodo.Value.Month, 1);
            DateTime diff = new DateTime((tmEnd - tmStart).Ticks);

            int numberOfFrames = (tmEnd.Year - tmStart.Year);
            Session["numberOfFrames"] = ((diff.Year - 1) * 12) + diff.Month;;

            this.ProcessarConteudoAnual(demandModels, DateTime.Now.Year);

            this.ExibirObservacao(string.Format(caption, DateTime.Now.Year));

            this.GerarGrafico();

            // Exibe a data da última atualização
            (this.Master.FindControl("LblUltimoUpdate") as Label).Text = "Última atualização em: " + this.Presenter.DemandListLastUpdate.ToShortDateString() + " as " + this.Presenter.DemandListLastUpdate.ToShortTimeString();

            (this.Master.FindControl("txtTimeToCompare") as HtmlGenericControl).InnerHtml =
                this.Presenter.DemandListLastUpdate.Year + "," +
                (this.Presenter.DemandListLastUpdate.Month - 1) + "," +
                this.Presenter.DemandListLastUpdate.Day + "," +
                this.Presenter.DemandListLastUpdate.Hour + "," +
                this.Presenter.DemandListLastUpdate.Minute + "," +
                this.Presenter.DemandListLastUpdate.Second;   
        }

        private void GerarGrafico()
        {
            List<string> lines = new List<string>() { "Alocacao", "ForcaDesenvolvimento" };

            for (int i = 0; i < 2; i++)
            {
                chartAlocDisp.Series.Add(lines[i]);
                chartAlocDisp.Series[lines[i]].ChartArea = "MainChart";
                chartAlocDisp.Series[lines[i]].ChartType = System.Web.UI.DataVisualization.Charting.SeriesChartType.Line;

                for (int j = 0; j < sumarizadorTotal.Length; j++)
                {
                    System.Web.UI.DataVisualization.Charting.DataPoint dt;
                    if (i == 0)
                    {
                        chartAlocDisp.Series[lines[i]].Color = Color.Blue;
                        dt = new System.Web.UI.DataVisualization.Charting.DataPoint(j + 1, sumarizadorTotal[j]);
                        if (j == 0 || j % 2 == 0) dt.Label = sumarizadorTotal[j] + "h";
                            chartAlocDisp.Series[lines[i]].Points.Add(dt);
                    }
                    else
                    {
                        chartAlocDisp.Series[lines[i]].Color = Color.Red;
                        dt = new System.Web.UI.DataVisualization.Charting.DataPoint(j + 1, sumarizadorDisponibilidade[j]);
                        if (j == 0 || j % 2 == 0) dt.Label = sumarizadorDisponibilidade[j] + "h";                        
                            chartAlocDisp.Series[lines[i]].Points.Add(dt);
                    }
                }

            }
        }

        private void ProcessarConteudoAnual(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels, int year)
        {
            List<string> teamProjects = new List<string>() { "TeamProjectsSinacor", "TeamProjectsIMercado", "TeamProjectsSiteBVMF" };
            
            sumarizadorTotal = new int[52];
            foreach (string str in teamProjects)
            {
                var demandGroups =
                       from d in demandModels
                       where    (
                                    this.Presenter.CheckExistsWithin(d.Project, str)
                                    &&
                                    (d.EstimatedStart.Value.Year == year || d.EstimatedConclude.Value.Year == year)
                                    && 
                                    d.State != "Cancelada"
                                )
                                ||
                                (
                                    (d.State == "Cancelada" && d.UsedHours != 0)
                                    &&
                                    this.Presenter.CheckExistsWithin(d.Project, str)
                                    &&
                                    (d.EstimatedStart.Value.Year == year || d.EstimatedConclude.Value.Year == year)
                                )
                       group d by d.Project into g
                       select new { Project = g.Key, Demands = g };

                int subGroups = demandGroups.ToList().Count;

                int counter = demandGroups.ToList().Count;

                this.GerarHeader(counter, str, parentDiv);

                sumarizadorModulo = new int[52];

                for (int i = 0; i < subGroups; i++)
                {
                    this.CarregarConteudoAnual(demandGroups.ToList()[i].Demands, year, str);
                    this.parentDiv.Controls.Add(new LiteralControl("<br />"));                    
                }

                this.GerarTotalModulo(str);
            }

            sumarizadorDisponibilidade = new int[52];

            GerarHeaderTotal(1, year);
            GerarTotalAlocacao(1);
            GerarTotalDisponibilidade(1, year);
            GerarTotalDiferenca(1);

            this.totalGeralDiv.Controls.Add(new LiteralControl("<br />"));

            GerarHeaderTotal(2, year);
            GerarTotalAlocacao(2);
            GerarTotalDisponibilidade(2, year);
            GerarTotalDiferenca(2);

            this.totalGeralDiv.Controls.Add(new LiteralControl("<br />"));
        }

        private void GerarTotalDiferenca(int part)
        {
            int numberOfCols = 26;

            Table tbl = new Table();
            TableRow r;
            TableCell c;

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "2");
            tbl.Style.Add("background-color", "#FFFFFF");

            r = new TableRow();

            r.Style.Add("background-color", "#FFFFFF");
            r.Style.Add("font-family", "Verdana");
            r.Style.Add("font-size", "X-Small");

            for (int j = 0; j <= numberOfCols; j++)
            {

                r.Style.Add("align", "left");
                r.Style.Add("background-color", "#CFCFCF");
                r.Style.Add("font-family", "Verdana");
                r.Style.Add("font-size", "X-Small");

                if (j == 0)
                {
                    c = new TableCell();
                    c.Style.Add("font-weight", "bold");
                    c.Style.Add("text-align", "left");
                    c.Width = 120;
                    c.Controls.Add(new LiteralControl("HORAS DISPONIVEIS:"));
                    r.Cells.Add(c);
                }
                else
                {
                    c = new TableCell();
                    c.Style.Add("text-align", "center");

                    int dia = 0;
                    if (part == 1)
                        dia = j;
                    else
                        dia = (26 + j);

                    int hours = ((sumarizadorTotal[dia - 1]) - (sumarizadorDisponibilidade[dia - 1])) * -1;

                    if (hours >= 0)
                    {
                        c.Style.Add("background-color", "#FF3300");//"#33CC33");                        
                    }
                    else
                    {
                        c.Style.Add("background-color", "#33CC33");//"#FF3300");                        
                    }

                    c.Controls.Add(new LiteralControl(hours + ""));

                    c.Width = 40;
                    r.Cells.Add(c);
                }

            }
            tbl.Rows.Add(r);
            totalGeralDiv.Controls.Add(tbl);
        }

        private void GerarTotalDisponibilidade(int part, int year)
        {
            List<DateTime> feriados = (List<DateTime>)Session["feriados"];

            List<DeveloperModel> devsCDSB =
                    this.Presenter.Developers.ToList().FindAll(
                    delegate(DeveloperModel md)
                    {
                        bool forTeam = md.DeveloperTeam != "Suporte 3º Nível";
                        bool forMission = (md.Mission == Mission.Developer);
                        bool forCDSB = (md.DeveloperTeam.ToLower().Contains("time"));

                        return (forTeam && forMission && forCDSB);
                    });

            List<DeveloperModel> devs7Comm =
                this.Presenter.Developers.ToList().FindAll(
                delegate(DeveloperModel md)
                {
                    bool forTeam = md.DeveloperTeam != "Suporte 3º Nível";
                    bool forMission = (md.Mission == Mission.Developer);
                    bool forCDSB = (md.DeveloperTeam == "7COMm-VCoding");


                    //HC
                    bool list = (md.DeveloperName != "Ubiratan Radanovic Vieira");

                    return (forTeam && forMission && forCDSB && list);
                });

            int numberOfCols = 26;

            Table tbl = new Table();

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "2");
            tbl.Style.Add("background-color", "#333333");

            TableRow r = new TableRow();
            r.Style.Add("align", "left");
            r.Style.Add("background-color", "#99CCFF");
            r.Style.Add("font-family", "Verdana");
            r.Style.Add("font-size", "X-Small");

            TableCell c = new TableCell();
            c.Width = 120;
            c.Style.Add("text-align", "left");
            c.Controls.Add(new LiteralControl("FORÇA DESENVOLVIMENTO:"));

            r.Cells.Add(c);

            for (int j = 0; j < numberOfCols; j++)
            {
                c = new TableCell();
                c.Style.Add("text-align", "center");

                int dia = 0;

                if (part == 1)
                    dia = j;
                else
                    dia = (26 + j);

                int hoursCDSB = 0;
                int hours7Comm = 0;

                DateTime dt = new DateTime(year, 1, 1).AddDays(7 * (dia));
                while (dt.DayOfWeek != DayOfWeek.Monday)
                {
                    dt = dt.AddDays(1);
                }

                DateTime dtFim = dt.AddDays(4);

                //string aux = "<a title='" + dt.ToShortDateString() + "-" + dtFim.ToShortDateString() + "'>" + (dia + 1) + "</a>";
                //c.Controls.Add(new LiteralControl("" + aux));

                while (dt.Date <= dtFim.Date)
                {
                    if (
                        (!feriados.Contains(dt.Date))
                        &&
                        (dt.DayOfWeek != DayOfWeek.Saturday && dt.DayOfWeek != DayOfWeek.Sunday)
                       )
                    {
                        hoursCDSB +=
                             devsCDSB.FindAll(delegate(DeveloperModel d)
                        {
                            List<DateTime> lstDataInterna = new List<DateTime>();

                            d.Dayof.ForEach(delegate(string strData)
                            {
                                lstDataInterna.Add(DateTime.Parse(strData.Split('|')[0]));
                            });

                            bool porFolga = lstDataInterna.Contains(dt.Date);
                            bool porFerias = (
                                (d.StartFreeDaysPaid.HasValue && d.FinishFreeDaysPaid.HasValue)
                                &&
                                (dt.Date >= d.StartFreeDaysPaid.Value.Date && dt.Date <= d.FinishFreeDaysPaid.Value.Date)
                                                );

                            bool porInicio = false;

                            if (d.DeveloperStartAt.HasValue)
                                porInicio = dt.Date < d.DeveloperStartAt.Value.Date;

                            return (!porFolga && !porFerias && !porInicio);
                        }).Count;

                        //dt = dt.AddDays(1);

                        hours7Comm +=
                             devs7Comm.FindAll(delegate(DeveloperModel d)
                             {
                                 List<DateTime> lstDataInterna = new List<DateTime>();

                                 d.Dayof.ForEach(delegate(string strData)
                                 {
                                     lstDataInterna.Add(DateTime.Parse(strData.Split('|')[0]));
                                 });

                                 bool porFolga = lstDataInterna.Contains(dt.Date);
                                 bool porFerias = (
                                     (d.StartFreeDaysPaid.HasValue && d.FinishFreeDaysPaid.HasValue)
                                     &&
                                     (dt.Date >= d.StartFreeDaysPaid.Value.Date && dt.Date <= d.FinishFreeDaysPaid.Value.Date)
                                                     );
                                 
                                 bool porInicio = false;

                                 if (d.DeveloperStartAt.HasValue)
                                     porInicio = dt.Date < d.DeveloperStartAt.Value.Date;

                                 return (!porFolga && !porFerias && !porInicio);
                             }).Count;
                    }

                    dt = dt.AddDays(1);

                }

                hoursCDSB = hoursCDSB * 8;
                hours7Comm = hours7Comm * 8;

                int countHours = (hoursCDSB + hours7Comm);

                string write = "<a title='" + hoursCDSB + " horas disponiveis CDSB / " + hours7Comm + " horas disponiveis 7Comm.'>" + countHours + "h</a>";

                sumarizadorDisponibilidade[dia] = countHours;

                c.Controls.Add(new LiteralControl(write));

                c.Width = 40;
                r.Cells.Add(c);
            }

            tbl.Rows.Add(r);
            totalGeralDiv.Controls.Add(tbl);
        }

        private void GerarTotalAlocacao(int part)
        {
            int numberOfCols = 26;

            Table tbl = new Table();
            TableRow r;
            TableCell c;

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "2");
            tbl.Style.Add("background-color", "#333333");

            r = new TableRow();

            r.Style.Add("background-color", "#FFFFFF");
            r.Style.Add("font-family", "Verdana");
            r.Style.Add("font-size", "X-Small");

            for (int j = 0; j <= numberOfCols; j++)
            {

                r.Style.Add("align", "left");
                r.Style.Add("background-color", "#FFFF99");
                r.Style.Add("font-family", "Verdana");
                r.Style.Add("font-size", "X-Small");

                if (j == 0)
                {
                    c = new TableCell();
                    c.Width = 120;
                    c.Style.Add("text-align", "left");
                    c.Controls.Add(new LiteralControl("HORAS ALOCADAS:"));
                    r.Cells.Add(c);
                }
                else
                {
                    c = new TableCell();
                    c.Style.Add("text-align", "center");

                    int dia = 0;
                    if (part == 1)
                        dia = j;
                    else
                        dia = (26 + j);

                    c.Controls.Add(new LiteralControl(sumarizadorTotal[dia - 1] + "h"));
                    c.Width = 40;
                    r.Cells.Add(c);
                }

            }
            tbl.Rows.Add(r);
            totalGeralDiv.Controls.Add(tbl);
        }

        private void GerarHeaderTotal(int part, int year)
        {
            int numberOfCols = 26;

            Table tbl = new Table();
            TableRow r;
            TableCell c;

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "2");
            tbl.Style.Add("background-color", "#333333");

            r = new TableRow();

            r.Style.Add("background-color", "#FFFFFF");
            r.Style.Add("font-family", "Verdana");
            r.Style.Add("font-size", "X-Small");

            for (int j = 0; j <= numberOfCols; j++)
            {

                r.Style.Add("align", "left");
                r.Style.Add("background-color", "#CFCFCF");
                r.Style.Add("font-family", "Verdana");
                r.Style.Add("font-size", "X-Small");

                if (j == 0)
                {
                    c = new TableCell();
                    c.Style.Add("font-weight", "bold");
                    c.Style.Add("text-align", "left");
                    c.Width = 120;
                    c.Controls.Add(new LiteralControl("SEMANA:"));
                    r.Cells.Add(c);
                }
                else
                {
                    c = new TableCell();
                    c.Style.Add("font-weight", "bold");
                    c.Style.Add("text-align", "center");

                    int dia = 0;
                    if (part == 1)
                        dia = j;
                    else
                        dia = (26 + j);

                    DateTime dt = new DateTime(year, 1, 1).AddDays(7 * (dia - 1));
                    while (dt.DayOfWeek != DayOfWeek.Monday)
                    {
                        dt = dt.AddDays(1);
                    }

                    DateTime dtFim = dt.AddDays(4);

                    string aux = "<a title='" + dt.ToShortDateString() + "-" + dtFim.ToShortDateString() + "'>" + (dia) + "</a>";
                    c.Controls.Add(new LiteralControl("" + aux));

                    c.Width = 40;
                    r.Cells.Add(c);
                }

            }
            tbl.Rows.Add(r);
            totalGeralDiv.Controls.Add(tbl);
        }

        private void GerarTotalModulo(string str)
        {
            Table tbl = new Table();
            tbl.Width = new Unit(2200);
            TableRow r = new TableRow();
            TableCell c;

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "0");
            tbl.Style.Add("background-color", "#333333");
            
            r.Style.Add("align", "left");
            r.Style.Add("background-color", "#FFFF99");
            r.Style.Add("font-family", "Verdana");
            r.Style.Add("font-size", "X-Small");

            for (int i = 0; i < sumarizadorModulo.Length + 1; i++)
            {
                c = new TableCell();

                if (i == 0)
                {
                    c.Style.Add("font-weight", "bold");
                    c.Width = 120;
                    c.Controls.Add(new LiteralControl(str.Replace("TeamProjects","")));
                }
                else
                {
                    c.Width = 40;
                    c.Style.Add("text-align", "center");
                    c.Controls.Add(new LiteralControl(sumarizadorModulo[i - 1] + "h"));

                    sumarizadorTotal[i - 1] += sumarizadorModulo[i - 1];
                }

                r.Cells.Add(c);
            }

            tbl.Rows.Add(r);
            parentDiv.Controls.Add(tbl);
            parentDiv.Controls.Add(new LiteralControl("<br />"));                    
        }        

        private void ExibirObservacao(string obs)
        {
            this.LblObsOrdenacao.Text = obs;
            this.LblObsOrdenacao.Visible = this.LblObsOrdenacao.Text.Length > 0 ? true : false;
        }

        private void GerarHeader(int counter, string str, HtmlGenericControl ctr)
        {
            Table tbl = new Table();
            tbl.Width = new Unit(1024);
            tbl.Style.Add("text-align", "left");
            //tbl.Style.Add("margin-left", "5%");
            //tbl.Style.Add("margin-right", "1%");            

            TableRow r;
            TableCell c;

            if (counter != 0)
            {
                //Header

                r = new TableRow();

                r.Style.Add("background-color", "#FFFFFF");
                r.Style.Add("font-family", "Verdana");
                r.Style.Add("font-size", "Small");

                c = new TableCell();
                c.Style.Add("font-weight", "bold");
                c.Style.Add("text-align", "left");
                c.Controls.Add(new LiteralControl(str));
                r.Cells.Add(c);

                tbl.Rows.Add(r);
                ctr.Controls.Add(tbl);

                //Header
            }
        }

        private void CarregarConteudoAnual(IEnumerable<DemandModel> col, int year, string TeamProject)
        {
            List<DemandModel> lst = col.ToList();
            string Modulo = lst.First(delegate(DemandModel d) { return true; }).Project;
            int numberOfCols = 52;

            sumarizador = new int[numberOfCols];

            Table tbl = new Table();
            tbl.Width = new Unit(2200);
            TableRow r = new TableRow();
            TableCell c;

            tbl.Attributes.Add("cellspacing", "1");
            tbl.Attributes.Add("cellpadding", "0");
            tbl.Style.Add("background-color", "#333333");

            for (int i = 0; i < (lst.Count + 1); i++)
            {
                r = new TableRow();

                if (i == 0)
                {
                    r.Style.Add("background-color", "#CFCFCF");
                    r.Style.Add("font-family", "Verdana");
                    r.Style.Add("font-size", "X-Small");
                }
                else
                {
                    r.Style.Add("background-color", "#FFFFFF");
                    r.Style.Add("font-family", "Verdana");
                    r.Style.Add("font-size", "X-Small");
                }

                for (int j = 0; j <= numberOfCols; j++)
                {
                    if (i == 0)
                    {
                        if (j == 0)
                        {
                            c = new TableCell();
                            c.Style.Add("font-weight", "bold");
                            c.Style.Add("text-align", "left");
                            c.Controls.Add(new LiteralControl(Modulo));
                            c.Width = 120;
                            r.Cells.Add(c);
                        }
                        else
                        {
                            c = new TableCell();
                            c.Style.Add("font-weight", "bold");
                            c.Style.Add("text-align", "center");
                            c.Controls.Add(new LiteralControl("" + j));
                            c.Width = 40;
                            r.Cells.Add(c);
                        }
                    }
                    else
                    {
                        if (j == 0)
                        {
                            c = new TableCell();
                            //c.Style.Add("font-weight", "bold");
                            c.Style.Add("text-align", "left");
                            string TaskId = "<a title='" + lst[i - 1].Title + "'>" + lst[i - 1].ID + "</a>";
                            c.Controls.Add(new LiteralControl(TaskId));
                            c.Width = 120;
                            r.Cells.Add(c);
                        }
                        else
                        {
                            c = new TableCell();
                            c.Style.Add("font-weight", "bold");
                            c.Style.Add("text-align", "center");

                            DateTime dt = new DateTime(year, 1, 1).AddDays(7*(j -1));

                            while (dt.DayOfWeek != DayOfWeek.Monday)
                            {
                                dt = dt.AddDays(1);
                            }

                            DateTime dtFim = dt.AddDays(6);

                            int NumeroHorasTasksNaSemana = this.CalcularNumeroHorasTasksNaSemana(dt, dtFim, lst[i - 1]);

                            c.Controls.Add(new LiteralControl("" + NumeroHorasTasksNaSemana));

                            sumarizador[j -1] += NumeroHorasTasksNaSemana;
                            sumarizadorModulo[j - 1] += NumeroHorasTasksNaSemana;

                            c.Width = 40;
                            r.Cells.Add(c);
                        }
                    }
                }

                tbl.Rows.Add(r);
            }

            tbl.Rows.Add(this.AddSubTotal(Modulo));

            parentDiv.Controls.Add(tbl);
        }

        private TableRow AddSubTotal(string Modulo)
        {
            TableRow r = new TableRow();
            TableCell c = new TableCell();

            r.Style.Add("align", "left");
            r.Style.Add("background-color", "#FFFF99");
            r.Style.Add("font-family", "Verdana");
            r.Style.Add("font-size", "X-Small");

            for (int i = 0; i < sumarizador.Length + 1; i++)
            {
                c = new TableCell();

                if (i == 0)
                {
                    c.Style.Add("font-weight", "bold");
                    c.Width = 120;
                    c.Style.Add("text-align", "left");
                    c.Controls.Add(new LiteralControl("Total:"));
                }
                else
                {
                    c.Width = 40;
                    c.Style.Add("text-align", "center");
                    c.Controls.Add(new LiteralControl(sumarizador[i-1] + "h"));
                }

                r.Cells.Add(c);
            }

            return r;
        }

        private int CalcularNumeroHorasTasksNaSemana(DateTime dt, DateTime dtFim, DemandModel item)
        {
            DateTime inicioTask = item.EstimatedStart.Value;
            DateTime fimTask = item.EstimatedConclude.Value;

            int NumeroHorasTasksNaSemana = 0;

            while (dt.Date <= dtFim.Date)
            {
                if (this.DataNoPeriodo(dt, inicioTask, fimTask))
                    NumeroHorasTasksNaSemana += 8;
                
                dt = dt.AddDays(1);
            }

            return NumeroHorasTasksNaSemana;
        }

        private bool DataNoPeriodo(DateTime dt, DateTime inicioTask, DateTime fimTask)
        {
            List<DateTime> feriados = (List<DateTime>)Session["feriados"];

            List<DateTime> lst = new List<DateTime>();
            while (inicioTask.Date <= fimTask.Date)
            {
                if(
                    (!feriados.Contains(inicioTask.Date))
                    &&
                    (inicioTask.DayOfWeek != DayOfWeek.Saturday && inicioTask.DayOfWeek != DayOfWeek.Sunday)
                    )
                    lst.Add(inicioTask.Date);

                inicioTask = inicioTask.AddDays(1);
            }

            return lst.Contains(dt.Date);
        }

        public void GeneratePaginator(int totalPages)
        {
            if (cboMonths.Items.Count == 0)
            {
                DateTime? dtInicioPeriodo = ((IEnumerable<DemandModel>)Session["demandModels"]).Min(x => x.EstimatedStart);
                DateTime tmStart = new DateTime(dtInicioPeriodo.Value.Year, dtInicioPeriodo.Value.Month, 1);
                
                for (int i = 0; i < totalPages; i++)
                {
                    cboMonths.Items.Add(tmStart.AddMonths(i).Month + "/" + tmStart.AddMonths(i).Year);                    
                }

                cboMonths.Items.Add("Relatório Anual");

                cboMonths.SelectedIndex = (cboMonths.Items.Count - 1);
            }
        }

        protected void cboMonths_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["comboSelectedMonth"] = cboMonths.SelectedIndex;
            Response.Redirect("Alocacao.aspx");            
        }

        #region IDiscriminatorDemand Members

        void IDiscriminatorDemand.ExibirFila(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirEsteira(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirRanking(IEnumerable<CDSBDemandControl.Model.DeveloperModel> developers, IEnumerable<CDSBDemandControl.Model.DeveloperModel> leaders, IEnumerable<CDSBDemandControl.Model.DeveloperModel> focalpoints)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirAtrasos(IEnumerable<CDSBDemandControl.Model.DemandModel> PendingDemands, IEnumerable<CDSBDemandControl.Model.DemandModel> Concludeddemands)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFaturamento(List<CDSBDemandControl.Model.BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirCodeReview(IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithCodeReview, IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithoutCodeReview)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducao(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirListaDisp(IEnumerable<CDSBDemandControl.Model.DemandModel> list, IEnumerable<CDSBDemandControl.Model.DeveloperModel> modelAusencias, List<DateTime> fer)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducaoUltimoMes(List<CDSBDemandControl.Model.DemandModel> BugList)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryWaitingList(List<CDSBDemandControl.Model.BillingModel> Billing, bool AllowsShow)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryProductionList(List<BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirSolicitacoesSites(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirManagementTeamTasks(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirScenariosAndTasks(List<CDSBDemandControl.Model.ScenarioModel> scenarios)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
